<?php

abstract class App_Kernel
{
	protected $_config = null;
	protected $_appRoot = null;
	protected $_frontController = null;
	protected $_auth = null;
	protected $_acl = null;
	protected $_router = null;
	
	public function __construct($appRoot, $config)
	{
        $cnf = new Zend_Config($config);
        Zend_Registry::set('cnf', $cnf); 

        $this->_appRoot = $appRoot;
        $this->_config = $cnf;
	}
	
	public function setupFrontController()
	{
		$fc = Zend_Controller_Front::getInstance();
		$fc->setBaseUrl($this->_config->url->base);
		$fc->setControllerDirectory(array(
		    'default' => $this->_config->path->modules->default,
		    'admin'   => $this->_config->path->modules->admin
		));
		$fc->setParam('auth', $this->_auth);
		$fc->setParam('acl', $this->_acl);
		$fc->registerPlugin(
		    new App_Controller_Plugin_Acl($this->_auth, $this->_acl)
		);
		$fc->setRouter($this->_router);
		//$fc->throwExceptions(true);
		
		$this->_frontController = $fc;
	}

    public function setupAcl()
    {	
        $this->_auth = Zend_Auth::getInstance();
        $this->_acl = new Acl($this->_auth);
    }
    
	public function setupRoutes()
	{
		$this->_router = new Zend_Controller_Router_Rewrite();
		$this->_router->addRoutes(require_once 'routes.php');
	}
	
	public function setupView()
	{
		$layout = Zend_Layout::startMvc(array(
		    'layoutPath' => $this->_config->path->layouts,
		    'pluginClass' => 'App_Layout_Controller_Plugin_Layout'
		));
		$view = $layout->getView();
		$view->baseUrl = $this->_config->url->base;
		$view->setBasePath($this->_config->path->views);
		$view->setEncoding('UTF-8');
		$view->doctype('XHTML1_STRICT');
		$view->addHelperPath($this->_config->path->helpers, 'App_View_Helper_');
		$layout->setView($view);		
	}
	
	public function setupZendDb()
	{
        $dbAdapter = Zend_Db::factory($this->_config->db);
        Zend_Db_Table::setDefaultAdapter($dbAdapter);
	}
	
    public function run()
    {
    	Zend_Session::start();
    	
    	$this->setupZendDb();
    	$this->setupRoutes();
    	$this->setupAcl();
    	$this->setupView();
    	$this->setupFrontController();
    	
    	$this->_frontController->dispatch();
    	
//        try {
//            $this->_frontController->dispatch();
//        }
//        catch(Exception $e) {
//            echo nl2br($e->__toString());
//        }         
    }	
}
